package com.xwzj.collects.spider.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.Test;

/**
 * 
 * @author xianfeng.cai
 * @date 2019-04-04
 */
public class JsoupDemo {

    @Test
    public void login() throws Exception {
    	Connection con = Jsoup.connect("http://127.0.0.1:8888");
        Response rs = con.execute();
        System.out.println(rs.cookies());
        Document d1 = Jsoup.parse(rs.body());
        List<Element> et = d1.select("form");
        Map<String, String> datas = new HashMap<>();
        for (Element e : et.get(0).getAllElements()) {
            if (e.attr("name").equals("loginName")) {
                e.attr("value", "admin");// 设置用户名
            }
            if (e.attr("name").equals("password")) {
                e.attr("value", "admin"); // 设置用户密码
            }
        }
        datas.put("loginName", "admin");
        datas.put("password", "admin");
        Connection con2 = Jsoup.connect("http://127.0.0.1:8888/login");
        Response login = con2.ignoreContentType(true).method(Method.POST).data(datas).cookies(rs.cookies()).execute();
        System.out.println(login.body());
    }

}
